package com.hc.kotlin_coroutine

import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.asContextElement
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield

fun main15() = runBlocking<Unit> {
    val job = launch {
        println("job is ${coroutineContext[Job]}")
    }
    val parentCoroutine = launch {
        val childCoroutineOne = GlobalScope.launch {
            println("childCoroutineOne start")
            delay(1000)
            println("childCoroutineOne end")
        }
        val childCoroutineTwo = launch {
            println("childCoroutineTwo start")
            delay(1000)
            println("childCoroutineTwo end")
        }
    }
    delay(500)
    parentCoroutine.cancel()//父协程取消时 GlobalScope协程不受父协程影响 普通子协程取消
    delay(1000)
    println("all quit")
}
fun main16() = runBlocking<Unit> {
    val parent = launch {
        repeat(3){
            launch {
                delay((it+1)*500L)
                println("${Thread.currentThread().name} ${it} is finish")
            }
        }
        println("all finish")
        launch(CoroutineName("CustomCoroutineName")){ //命名协程
            delay(500)
            println("${Thread.currentThread().name} async is finish")
        }
        launch(Dispatchers.Default + CoroutineName("CustomCoroutineName2")) {//多元素指定
            delay(500)
            println("${Thread.currentThread().name} async is finish")
        }
    }
//    parent.join()  //非必要调用 父协程总是等待子协程执行结束
    println("all quit")
}
val threadLocal = ThreadLocal<String?>()
fun main() = runBlocking<Unit> {
    threadLocal.set("main")
    println("step1 ${Thread.currentThread()}, value ${threadLocal.get()}")
    val job = launch(Dispatchers.Default+ threadLocal.asContextElement(value = "launch")) {//线程局部数据传递
        println("step2 ${Thread.currentThread()},value ${threadLocal.get()}")
        yield()
        println("step3 ${Thread.currentThread()},value ${threadLocal.get()}")
    }
    job.join()
    println("step4 ${Thread.currentThread()},value ${threadLocal.get()}")
}